package cn.yx.common.core.util.reflect;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * <p>Bean工具类</p>
 *
 * @author Wgssmart
 */
public final class BeanUtil {

    private BeanUtil() {
    }

    /**
     * 把FROM中非null值拷贝到TO中属性名一样且属性值为null的属性
     *
     * @param from   源对象
     * @param to     目标对象
     * @param <FROM> FROM源对象
     * @param <TO>   TO目标对象
     * @return
     */
    public static <FROM, TO> TO copyValueToNull(FROM from, TO to) {
        Field[] fromFields = from.getClass().getDeclaredFields();
        for (Field field : fromFields) {
            String name = field.getName();
            Object fromValue = ReflectUtil.invokeGetter(from, name);
            Object toValue = ReflectUtil.invokeGetter(to, name);
            if (Objects.nonNull(fromValue) && Objects.isNull(toValue)) {
                ReflectUtil.invokeSetter(to, name, fromValue);
            }
        }
        return to;
    }
}
